import type { AddressItem } from "@/types/address"
import { defineStore } from "pinia"
import { ref } from "vue"
import { getMemberAddressAPI } from '@/services/address'

export const useAddressStore = defineStore('address',()=>{
    const selectedAddress = ref<AddressItem>()
    const addressList = ref<AddressItem[]>([])
    const changeSelectedAddress = (val: AddressItem) => {
        selectedAddress.value = val
    }
    const loadAddressList = async () => {
        const res = await getMemberAddressAPI()
        addressList.value = res.result
        // 如果有默认地址，优先选择默认地址
        const defaultAddress = addressList.value.find(item => item.isDefault === 1)
        if (defaultAddress) {
            changeSelectedAddress(defaultAddress)
        } else if (addressList.value.length > 0) {
            // 否则选择第一个地址
            changeSelectedAddress(addressList.value[0])
        }
    }
    return {
        selectedAddress,
        addressList,
        changeSelectedAddress,
        loadAddressList
    }
})